package git.soulbgm.common.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import git.soulbgm.common.exception.DecryptException;
import git.soulbgm.pojo.RsaVo;
import git.soulbgm.utils.AesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * 解密Http输入消息
 *
 * @author SoulBGM
 * @date 2023-10-08
 */
public class DecryptHttpInputMessage implements HttpInputMessage {

    private static final Logger log = LoggerFactory.getLogger(DecryptHttpInputMessage.class);

    private final HttpHeaders headers;

    private InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, ObjectMapper mapper, String uniqueKey) throws IOException {
        // 这里是body 读取之前的处理
        this.headers = inputMessage.getHeaders();
        // 从inputStreamReader 得到aes 加密的内容
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody())).lines().collect(Collectors.joining(System.lineSeparator()));
        RsaVo vo = mapper.readValue(content, RsaVo.class);
        String data = vo.getData();
        if (data == null) {
            throw new DecryptException("解密异常，格式有误");
        }
        try {
            // 1、rsa解码
            String decryptBody = AesUtil.decrypt(data, uniqueKey);
            if (!StringUtils.isEmpty(decryptBody)) {
                // 2、重新写入到controller
                this.body = new ByteArrayInputStream(decryptBody.getBytes(StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            log.error("解密时出现异常", e);
            throw new DecryptException("解密失败");
        }
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
